package com.bootdo.download.controller;

import java.util.concurrent.ExecutionException;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.bootdo.Asyncer;
import com.bootdo.check.domain.DetectResult;
import com.bootdo.download.domain.UrlJsonModel;


@CrossOrigin
@RestController
@EnableAutoConfiguration
public class VideoDownloadResful {
	
	  @Autowired
	  Asyncer asy;

	
	// 解析算法
	@ResponseBody
	@RequestMapping(value = "/postUrlJson", method = RequestMethod.POST)
	Boolean parseConHtml(@RequestBody UrlJsonModel urljson) {
		System.out.println(urljson);
		synchronized(StaticSet.stack) {
			StaticSet.stack.add(urljson);
		}
		return true;	
	}
	
	
    public void start() throws InterruptedException {
    	   

	
    }
    
	@PostConstruct
	public void doCheck() {


		Thread thread = new Thread(() -> {
			int i = 0;
			while (true) {
				if (StaticSet.stack.size()>0 && StaticSet.f<=20) {
					 StaticSet.f =  StaticSet.f+1;
					 try {
						asy.doTask();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				} else if (StaticSet.f>=20){
					if (StaticSet.f!=i) {
					  System.out.println("并行任务大于20个请等待...");
					  i = StaticSet.f;
					}
				} else if (StaticSet.f>0){
					if (StaticSet.f!=i) {
					   System.out.println("有"+StaticSet.f+"下载任务在执行");
					   i = StaticSet.f;
					}
				}
				
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		         
			}

		});
		thread.setDaemon(true);
		thread.start();

	}

}
